import * as cart from '@/api/cart'
const state = {
  // 用户购物车数据
  userCart: [],
  // 购物车将要结算的商品
  buyUserCart: []
}

const mutations = {

  // 保存用户购物车数据
  SET_USERCART: (state, cartList) => {
    if (cartList) {
      cartList.forEach(element => {
        element.selected = 0
      })
    }
    state.userCart = cartList
  },

  SET_BUYUSERCART: (state, buyUserCart) => {
    state.buyUserCart = buyUserCart
  }
}

const actions = {
  addCart({ commit, dispatch, rootState }, obj) {
    return new Promise((resolve, reject) => {
      cart.addCart(obj).then(res => {
        dispatch('getCarts', rootState.user.userDetail.id).then(res => {
          commit('SET_USERCART', res.object)
          resolve()
        })
      }).catch(() => {
        reject()
      })
    })
  },

  // 获取用户购物车数据
  getCarts({ commit, state }, uid) {
    return new Promise((resolve, reject) => {
      cart.getCartList(uid).then(res => {
        commit('SET_USERCART', res.object)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
